// 与微信本身有关系的api，非通用api，单独写这里，为了后面适配支付宝小程序

import { getOpenIdApi } from './index'

// 授权校验，判断是否获得用户授权
export function getSetting (auth, onSuccess, onFail) {
  mpvue.getSetting({
    success: (res) => {
      if (res.authSetting[`scope.${auth}`]) {
        onSuccess(res)
      } else {
        onFail(res)
      }
    },
    fail: (res) => {
      console.log('wechatjs-getSetting', res)
      // TODO 抛出异常
    }
  })
}
// 请求获取用户信息
export function getUserInfo (onSuccess, onFail) {
  mpvue.getUserInfo({
    success: (res) => {
      const { userInfo } = res
      if (userInfo) {
        onSuccess(userInfo)
      } else { onFail(res) }
    },
    fail (res) {
      console.log('wechatjs-getUserInfo', res)
      // TODO 抛出异常
    }
  })
}
// 写这里是为了适配支付宝小程序(接口可能会不一样，所以抽离出来)
export function setStorageSync (key, data) {
  mpvue.setStorageSync(key, data)
}
export function getStorageSync (key) {
  return mpvue.getStorageSync(key)
}
export function removeStorageSync (key) {
  mpvue.removeStorageSync(key)
}
export function getOpenId (callback) {
  mpvue.login({
    timeout: 10000,
    success: async (result) => {
      if (result.code) {
        const code = result.code
        const { data: { data } } = await getOpenIdApi(code)
        setStorageSync('openId', data.openid)
        setStorageSync('sessionKey', data.session_key)
        callback && callback(data.openid)
      } else {
        console.log('wechat-getOpenId-success-else', result)
        // TODO 抛出异常
      }
    },
    fail: (err) => {
      console.log('wechat-getOpenId-err', err)
      // TODO 抛出异常
    }
  })
}
export function showLoading (title) {
  mpvue.showLoading({
    title: title,
    mask: true
  })
}
export function hideLoading () {
  mpvue.hideLoading()
}
export function showToast (title) {
  wx.showToast({
    title: title,
    icon: 'none',
    duration: 800,
    mask: true
  })
}
export function setNavigationBarTitle (title) {
  wx.setNavigationBarTitle({
    title,
    success: (result) => {
    }
  })
}
